(function () {

    var startId = $("#objectId").attr("value");
    var startFields = JSON.parse($("#columns").attr("value"));
    var tableName = $("#tableName").attr("value");
    var dsId = $("#dsId").attr("value");
    var objectChname = $("#objectChname").attr("value");
    var isEnglish = true;
    console.log(startId);
    console.log(startFields);
    console.log(tableName);
    console.log(dsId);

    window.currentFields = []; //当前元素字段
    window.currentSelectedFields = []; //当前被选择元素字段
    window.currentRelationObj = []; //当前关联的表
    
    
    var toolbar = new joint.ui.Toolbar({   //头部控制模块

        tools: [
            {
                type: 'button',
                name: 'undo',
                group: 'undo-redo',
                attrs: {
                    button: {
                        'id':'btn-undo',
                        'data-tooltip': '撤销',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },
            {
                type: 'button',
                name: 'redo',
                group: 'undo-redo',
                attrs: {
                    button: {
                        'id':'btn-redo',
                        'data-tooltip': '返回',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },

            {
                type: 'button',
                group: 'layout',
                name: 'layout',
                attrs: {
                    button: {
                        id: 'btn-layout',
                        'data-tooltip': '自动布局',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },
            {
                type: 'zoom-to-fit',
                name: 'zoom-to-fit',
                group: 'zoom',
                attrs: {
                    button: {
                        'data-tooltip': '自适应缩放',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },
            {
                type: 'label',
                name: 'zoom-slider-label',
                group: 'zoom',
                text: 'Zoom:'
            },
            {
                type: 'zoom-slider',
                name: 'zoom-slider',
                group: 'zoom'
            },
            
            {
                type: 'toggle',
                name: 'toggle',
                group: 'last',
            },

        ],
        references: {
            paperScroller: paperScroller,
        }
    });

    $('#app').prepend(toolbar.render().el);
    
  //中英文切换
    toolbar.on('toggle:change', function(value, event) {

        $.each(graph.getElements(),function(i,v){
        	var cell = v;
        	var view = paper.findViewByModel(v);
        	var currentColumn = view.$el.find(".columnName");
        	 	  	 
        	 //如果是中文
        	 if(value === true){
        		 isEnglish = false;
        		 cell.attributes.attrs.isEnglish = false; //是中文
        		 view.$el.find("tspan").text(cell.attributes.attrs.objectChname);
        		 $.each(currentColumn, function (i, v) {
            		 var columnchname = $(this).attr("data-columnchname");
                  
                     $(this).text(columnchname);

                 })
        	 }else {
        		 isEnglish = true;
        		 cell.attributes.attrs.isEnglish = true; //是英文
        		 view.$el.find("tspan").text(cell.attributes.attrs.tableName);
        		 
        		 $.each(currentColumn, function (i, v) {
            		 var columnchname = $(this).attr("data-columnname");
            	
                     $(this).text(columnchname);

                 })
        	 }
        	 
        	 cell.attributes.attrs.div.html = view.$el.find('.content').html();
        })
        var promptMsg = "";
    	value=== true?promptMsg="已切换为中文":promptMsg = "已切换为英文";
        layer.msg(promptMsg,{time:1500})
    });
    
//单击元素
    paper.on('cell:pointerclick', function (cellView) {
        console.log(cellView.model);
//halo组件初始化
        var halo = new joint.ui.Halo({theme: 'modern', cellView: cellView});
//link没有halo组件
        if (cellView.model instanceof joint.shapes.app.Link) return;
//元素只连接元素
        halo.on('action:link:add', function (link) {
            if (!link.get('source').id || !link.get('target').id) {
                link.remove();
            }
        });
        halo.removeHandle('clone');
        halo.removeHandle('fork');
        halo.removeHandle('unlink');
        halo.removeHandle('rotate');
        halo.removeHandle('link');
        halo.removeHandle('remove');
        halo.render();
        if (cellView.model.attributes.type === "bpmn.Choreography") {  //如果是展开表数据
//自定义删除图标
            if (cellView.model.id !== startId) {   //初始元素不能删除
                halo.addHandle({
                    name: 'remove', position: 'nw', icon: '/assets/custom/draw/img/shanchu.svg', attrs: {
                        '.handle': {
                            'data-tooltip-class-name': 'small',
                            'data-tooltip': '删除',
                            'data-tooltip-position': 'right'
                        }
                    }
                });

//自定义筛选字段图标
                halo.addHandle({
                    name: 'filter', position: 'n', icon: '/assets/custom/draw/img/filter.svg', attrs: {
                        '.handle': {
                            'data-tooltip-class-name': 'small',
                            'data-tooltip': '筛选字段',
                            'data-tooltip-position': 'bottom'
                        }
                    }
                });
            }
//自定义展开子表图标
            halo.addHandle({
                name: 'changeTable', position: 'ne', icon: '/assets/custom/draw/img/changeTable.svg', attrs: {
                    '.handle': {
                        'data-tooltip-class-name': 'small',
                        'data-tooltip': '展开子表',
                        'data-tooltip-position': 'left'
                    }
                }
            });
/*
//自定义中英文切换
            halo.addHandle({
                name: 'languageChange', position: 'e', icon: '/assets/custom/draw/img/englishChange.svg', attrs: {
                    '.handle': {
                        'data-tooltip-class-name': 'small',
                        'data-tooltip': '中英文切换',
                        'data-tooltip-position': 'left'
                    }
                }
            });*/

//筛选字段事件
            halo.on('action:filter:pointerdown', function (evt) {
                evt.stopPropagation();
                window.currentFields = cellView.model.attributes.attrs.fields; //全部字段
                window.currentSelectedFields = cellView.model.attributes.attrs.selectFields;  //已选字段
                window.currentIsEnglish = isEnglish;  //是否是英文
                layer.open({
                    type: 2,
                    area: ["500px", "600px"],
                    content: '/assets/custom/draw/fieldFilter.html',
                    btn: ["确认", "取消"],
                    title: '筛选字段',
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find("iframe")[0]["name"]]; //子页面window
                        var selectFields = iframeWin.getCheckFieldData();                   //获取所有选中字段（调用子页面方法）

                        cellView.model.attributes.attrs.selectFields = selectFields;          //元素保存所有选中字段
                        modifyFieldLog(cellView.model, cellView.model.attributes.attrs.allFieldLog, false); //元素中的字段更新
                        layer.close(index);                                       //关闭窗口
                    }
                })
            });
//删除事件
            halo.on('action:remove:pointerdown', function (evt) {
                evt.stopPropagation();
                getOutboundElement(cellView.model, {outbound: true}); //删除所有outbound的元素
                cellView.model.remove();                            //当前元素删除
            });
//展开子表事件
            halo.on('action:changeTable:pointerdown', function (evt) {
                evt.stopPropagation();
                getRelationObj(cellView.model);
            });
/*
//切换语言事件
            halo.on('action:languageChange:pointerdown', function (evt) {
                evt.stopPropagation();

//需要切换的元素
                var currentColumn = cellView.$el.find(".columnName");
//如果是英文且切换成中文(反之)
                if (cellView.model.attributes.attrs.isEnglish) {
                    $.each(currentColumn, function (i, v) {

                        var columnchname = $(this).attr("data-columnchname");
                        $(this).text(columnchname);

                        cellView.model.attributes.attrs.isEnglish = false;

                        cellView.$el.find("tspan").text(cellView.model.attributes.attrs.objectChname);
                    })

                } else {

                    $.each(currentColumn, function (i, v) {

                        var columnName = $(this).attr("data-columnName");
                        $(this).text(columnName);
                        cellView.model.attributes.attrs.isEnglish = true;
                    });

                    cellView.$el.find("tspan").text(cellView.model.attributes.attrs.tableName);
                }
//model更新
                cellView.model.attributes.attrs[".content"].html = cellView.$el.find('.content').html();
            });*/
        }
    });

//点击记录(tr)
    $('.paperBox').on('click', '.content tbody tr', function () {

        var id = $(this).parents('.joint-cell').attr('model-id');       //得到当前的id

        if (id !== startId) {

            var contentStr = $(this).parents('.content').html();            //得到改变的contentStr
            var tbodyStr = $(this).parents('tbody').html();            //得到改变的tbody
            $(this).addClass('selectedLog').siblings().removeClass('selectedLog'); //当前的li标签被选中

//改变model
            var cell = graph.getCell(id);                                   //model
            cell.attributes.content = contentStr;                           //修改model的content
            cell.attributes.attrs[".content"].html = contentStr;             //修改model的content
            cell.attributes.attrs._tbody = tbodyStr;                     //修改model的tbodyStr
            cell.attributes.attrs._selectedLogNum = $(this).index();             //修改model的_selectedLogNum
            cell.attributes.attrs.currentLogObj = cell.attributes.attrs.allFieldLog[$(this).index()]; //修改当前的记录对象

//改变关联outbound的元素的记录
            var relationLink = graph.getConnectedLinks(cell, {outbound: true, inbound: false}); //获取当前元素关联outbound的线

            if (relationLink.length > 0) {
                recursionOutElementLog(cell, function () {
                    layer.msg('记录更新完成', {
                        time: 1500
                    })
                })
            }
        }


    });

//点击翻页
    $('.chainedEr').on('click', '.tableHref', function () {
        var id = $(this).parents('.joint-cell').attr('model-id');       //得到当前的id
        var cell = graph.getCell(id);

        var fields = cell.attributes.attrs.fields;                   //获取所有字段
        var requestColumnArr = $.map(fields, function (v, i) {
            return {"field": v};
        });                                                            //所有字段
        var queryId = cell.attributes.attrs._queryId;                   //翻页参数
        FilterFields({cell: cell, requestColumnArr: requestColumnArr, queryId: queryId});

    });

//元素初始化
    uploadTable({
        objectId: startId,
        startFields: startFields,
        tableName: tableName,
        dsId: dsId,
        objectChname: objectChname
    }, null);

//得到关系和表
    function getRelationObj(cell) {
        $.ajax({
            url: requestUrl + '/rest/dataObj/getRefLineByObjId',
            type: 'GET',
            dataType: 'JSON',
            data: {objectId: cell.attributes.objectId},
            success: function (result) {
//  console.log(result);
                window.currentRelationObj = []; //数组去重
                $.each(result.data, function (i, v) {
                    var relationObj = {
                        fkObj: {fkId: v.fkId, resource: cell.id, target: v.objectId, fkColumnList: v.fkColumnList},
                        dataObj: {
                            objectId: v.objectId,
                            objectChname: v.dataObj.objectChname,
                            tableName: v.dataObj.tableName,
                            table: v.dataObj.qTableName,
                            dsId: v.dataObj.dsId
                        }
                    };
                    currentRelationObj.push(relationObj);
//  console.log(relationObj);
                });

                layer.open({
                    type: 2,
                    area: ["500px", "600px"],
                    content: '/assets/custom/draw/relationTable.html',
                    btn: ["确认", "取消"],
                    title: '展开子表',
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find("iframe")[0]["name"]]; //子页面window
//   console.log(iframeWin.getCheckRelationData());

                        var data = iframeWin.getCheckRelationData();                //勾选的数据
                        var objId = $.map(data, function (v, i) {                    //勾选的全部对象id
                            return v.dataObj.objectId + v.fkObj.fkId;
                        });
                        var hadData = graph.getNeighbors(cell, {outbound: true});          //已经存在的数据
                        var hadDataId = $.map(hadData, function (v, i) {                    //已经存在全部对象id
                            return v.id;
                        });
//如果没有勾选就删除
                        $.each(hadData, function (i, v) {
                            if (objId.indexOf(v.id) === -1) {
                                v.remove();
                            }
                        });

//不重复加载
                        if (hadDataId.length > 0) {
                            hadDataId.forEach(function (v, i) {
                                data.forEach(function (value, index) {
                                    console.log(value);
                                    if (value.dataObj.objectId + value.fkObj.fkId === v) {
                                        data.splice(index, 1)
                                    }
                                })
                            });
                        }

//   console.log(data);
                        if (cell.id !== startId) {
                            var currentLog = cell.attributes.attrs.allFieldLog[cell.attributes.attrs._selectedLogNum]; //当前元素的选中记录
                        } else {
                            var currentLog = cell.attributes.attrs.currentLogObj
                        }
                        $.each(data, function (i, v) {

                            var whereLog = '';
                            $.each(v.fkObj.fkColumnList, function (index, value) {

                                if (index === 0) {
                                    whereLog += value.columnName + "= '" + currentLog[value.refColumnName] + "'";
                                } else {
                                    whereLog += 'and' + value.columnName + "= '" + currentLog[value.refColumnName] + "'";
                                }
// console.log(index);
                            });

                            v.where = whereLog;
//  console.log(v.where);
                            getTableObj({objId: v.dataObj.objectId}, v)
                        });


                        layer.close(index)
                    }
                })

            },
            error: function () {
                layer.msg('数据请求错误')
            }
        })
    }

//修改字段或者记录信息
    function modifyFieldLog(cell, data, isAddField) {

        var fields = cell.attributes.attrs.selectFields;  //已选字段
//thead数据填充
        var thead = '', thArr = [], th = '', thShowName;


        $.each(fields, function (i, v) {
//如果显示英文
            if (cell.attributes.attrs.isEnglish === true) {
                thShowName = v.columnName;
            } else {
                thShowName = v.columnChname;
            }

            th = '<th class="columnName" data-columnName="' + v.columnName + '" data-columnChname="' + v.columnChname + '">' + thShowName + '</th>';
            thArr.push(th);
        });


        thead = '<thead><tr>' + thArr.join("") + '</tr></thead>';  //thead字符串数据
//tbody数据填充
        var tbody = '', trArr = [], tr;
        $.each(data, function (i, v) { //遍历记录数据
            var that = v, tdArr = [], td = '';

            $.each(fields, function (i, v) {
                td = '<td>' + that[v.columnName] + '</td>';
                tdArr.push(td);
            });

            if (i === cell.attributes.attrs._selectedLogNum && !isAddField) {
                tr = '<tr class="selectedLog">' + tdArr.join("") + '</tr>';
            } else {
                tr = '<tr>' + tdArr.join("") + '</tr>';
            }

            trArr.push(tr);
        });

        if (isAddField) {
            var beforeTbody = cell.attributes.attrs._tbody; //获取之前的tbody
            tbody = '<tbody>' + beforeTbody + trArr.join("") + '</tbody>'; //tbody字符串数据
            cell.attributes.attrs.allFieldLog = cell.attributes.attrs.allFieldLog.concat(data); //model中allFieldLog更新

        } else {
            tbody = '<tbody>' + trArr.join("") + '</tbody>'; //tbody字符串数据
        }
        var tableStr = '<table>' + thead + tbody + '</table>';

        var view = paper.findViewByModel(cell);
        view.$el.find('table').html(tableStr);         //cellView中数据更新

        cell.attributes.attrs[".content"].html = view.$el.find('.content').html(); //model中数据更新
        cell.attributes.attrs._tbody = view.$el.find('tbody').html(); //model中tbody更新

    }

//筛选字段和记录信息
    function FilterFields(options, callback) {
        var cell = options.cell;
        var requestColumnArr = options.requestColumnArr;
        var queryId = options.queryId;
        var where = options.where;
        if (queryId) {
            $.ajax({
                url: requestUrl + '/api/browse/getData',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    table: cell.attributes.attrs._table,
                    dsId: cell.attributes.attrs._dsId,
                    tableHeads: JSON.stringify(requestColumnArr),
                    queryId: queryId
                },
                success: function (result) {
                    if (result.data.length > 0) {
                        modifyFieldLog(cell, result.data, true);
                        cell.attributes.attrs._queryId = result.queryId;
                    } else {
                        var view = paper.findViewByModel(cell);
                        view.$el.find('p.fr').remove();
                        var contentStr = view.$el.find('.content').html();         //cellView中数据更新
                        cell.attributes.attrs[".content"].html = contentStr;

                        layer.msg('没有更多数据', {
                            time: 1500
                        })
                    }

                },
                error: function (result) {
                    layer.msg('请求错误')
                }
            });
        } else if (where) {

            $.ajax({
                url: requestUrl + '/api/browse/getData',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    table: cell.attributes.attrs._table,
                    dsId: cell.attributes.attrs._dsId,
                    tableHeads: JSON.stringify(requestColumnArr),
                    where: where
                },
                success: function (result) {
                    console.log(result);
                    cell.attributes.attrs._selectedLogNum = 0;
                    modifyFieldLog(cell, result.data, false);
                    cell.attributes.attrs.allFieldLog = result.data;
                    callback && callback();
                },
                error: function (result) {
                    layer.msg('请求错误')
                }
            });
        }

    }

//修改首个元素(更换记录)
    window.modifyFirstElement = function (objId, data) {
//首个元素的字段变化
        var cell = graph.getCell(objId);
        var tr, trArr = [], objAllFields = {};
//判断当前元素是否显示英文

        $.each(data, function (i, v) {
            objAllFields[v.field] = v.value;

            if (cell.attributes.attrs.isEnglish === true) {
                var currentField = v.field
            } else {
                var currentField = v.columnChname
            }
            tr = '<tr><td class="columnName" data-columnName="' + v.field + '" data-columnChname="' + v.columnChname + '">' + currentField + '</td><td>' + v.value + '</td></tr>';
            trArr.push(tr)
        })
        cell.attributes.attrs.currentLogObj = objAllFields;
        var contentStr = '<table>' + trArr.join("") + '</table>';

        var view = paper.findViewByModel(cell);
        view.$el.find('.content').html(contentStr);         //cellView中数据更新

        cell.attributes.attrs[".content"].html = contentStr; //model中数据更新
        cell.attributes.attrs._tbody = view.$el.find('tbody').html(); //model中tbody更新


//所有outbound的变化

        var relationLink = graph.getConnectedLinks(cell, {outbound: true, inbound: false}); //关联的线
        if (relationLink.length > 0) { //存在关联的线
            recursionOutElementLog(cell)
        }
    };

//元素递归更新记录
    function recursionOutElementLog(cell, callback) {
        var list = [];
        list.push(cell.id);
        findRelateModel(cell);
        callback && callback();

        function findRelateModel(cell) {

            var relationLink = graph.getConnectedLinks(cell, {outbound: true, inbound: false}); //关联的线
            var current = cell.attributes.attrs.currentLogObj //当前的记录

            $.each(relationLink, function (i, v) {  //遍历不同的线

                var whereLog = '';  //条件参数
                var subCellId = v.attributes.dataObj.objectId + v.id; //关联元素的id

                var subCell = graph.getCell(subCellId);             //关联元素cell
                var requestColumnArr = $.map(subCell.attributes.attrs.fields, function (v, i) {
                    return {"field": v.columnName};
                });
                $.each(v.attributes.fkColumnList, function (index, value) { //遍历每条线关联的字段

                    if (index === 0) {
                        whereLog += value.columnName + "= '" + current[value.refColumnName] + "'";
                    } else {
                        whereLog += 'and' + value.columnName + "= '" + current[value.refColumnName] + "'";
                    }

                });


                if (list.indexOf(subCellId) === -1) {
                    list.push(subCellId);
                    FilterFields({cell: subCell, requestColumnArr: requestColumnArr, where: whereLog}, function () {
                        subCell.attributes.attrs.currentLogObj = subCell.attributes.attrs.allFieldLog[subCell.attributes.attrs._selectedLogNum];
                        findRelateModel(subCell);
                    });

                }

            });
        }

    }

//得到表数据
    function getTableObj(obj, relationObj) {
        var objId = obj.objId;
//获取表对象
            $.ajax({
                url: requestUrl + '/rest/dataObj/getObj',
                type: 'GET',
                dataType: 'JSON',
                data: {id: objId},
                success: function (result) {

                    var objectId = result.object.objectId; //对象的objectId
                    var dsId = result.object.dsId;          //disId
                    var qTableName = result.object.qTableName; //表名(参数)
                    var objectChname = result.object.objectChname; //中文表名
                    var tableName = result.object.tableName;    //英文表名
//获取字段信息
                    $.ajax({
                        url: requestUrl + '/rest/dataObj/getColumnsByObjId',
                        type: 'GET',
                        dataType: 'JSON',
                        data: {objectId: objectId},
                        success: function (result) {

                            var data = result.data;
                            var columnNameArr = []; //请求的全部字段
                            $.each(data, function (i, v) {
                                columnNameArr.push({
                                    columnName: v.columnName,
                                    columnChname: v.columnChname ? v.columnChname : v.columnName
                                })
                            });

                            var selectFields = columnNameArr.length > 3 ? columnNameArr.slice(0, 3) : columnNameArr;

                            var requestColumnArr = $.map(columnNameArr, function (v, i) {
                                return {"field": v.columnName}
                            });

//获取记录信息
                            $.ajax({
                                url: requestUrl + '/api/browse/getData',
                                type: 'POST',
                                dataType: 'JSON',
                                data: {
                                    table: qTableName,
                                    dsId: dsId,
                                    tableHeads: JSON.stringify(requestColumnArr),
                                    where: relationObj ? relationObj.where : null
                                },
                                success: function (result) {
                                var allFieldLog = result.data;
                                var queryId = result.queryId;
                                    var obj = {
                                        objectId : objectId,
                                        dsId : dsId,
                                        qTableName :qTableName,
                                        objectChname :objectChname,
                                        tableName :tableName,
                                        columnNameArr : columnNameArr,
                                        allFieldLog : allFieldLog,
                                        selectFields :selectFields,
                                        queryId : queryId,
                                    };

                                    uploadTable(obj,relationObj)
                                },
                                error: function () {
                                    layer.msg('访问错误')
                                }
                            })
                        }
                    })

                },
                error: function () {
                    layer.msg('访问错误')
                }
            })


    }

    //加载表对象
    function uploadTable(object, relationObj) {

        var objectId = object.objectId || null; //对象的objectId
        var dsId = object.dsId || null;          //disId
        var qTableName = object.qTableName || null; //表名(参数)
        var objectChname = object.objectChname ? object.objectChname : object.tableName || null; //中文表名
        var tableName = object.tableName || null;    //英文表名
        var columnNameArr = object.columnNameArr || null; //所有字段
        var allFieldLog = object.allFieldLog || null; //所有字段记录
        var selectFields = object.selectFields || null; //选择的字段
        var queryId = object.queryId || null; //翻页参数
        var startFields = object.startFields  || null; //单个元素的


        var obj = new joint.shapes.bpmn.Choreography({
            "type": "bpmn.Choreography",
            "participants": [
             isEnglish?tableName:objectChname
            ],
            "initiatingParticipant": "Potential Buyer",
            "position": {
                "x": 600,
                "y": 600
            },
            "angle": 0,
            "embeds": "",
            "z": 1,
            "id": !relationObj ? objectId : objectId + relationObj.fkObj.fkId,
            "objectId": objectId,
            "subProcess": false,
            "attrs": {
                ".participant-rect": {
                    "fill": "ff8040"
                },
                '.participant-label': {
                    'fill': '#fff'
                },
                ".sub-process": {
                    "visibility": "hidden",
                    "data-sub-process": ""
                },
                'div': {},
                '.body': {},
                '_dsId': dsId,
                'isEnglish': true,
                'objectChname': objectChname ? objectChname : tableName,
                'tableName': tableName,
            }
        });
        //如果有关联的表(不是加载首个元素)
        if(relationObj){
            //元素保存的参数
            obj.attributes.attrs.fields = columnNameArr;
            obj.attributes.attrs.selectFields = selectFields;
            obj.attributes.attrs.allFieldLog = allFieldLog;
            obj.attributes.attrs._table = qTableName;
            obj.attributes.attrs._queryId = queryId;
            obj.attributes.attrs._selectedLogNum = 0;
            obj.attributes.attrs._tbody = "";
            //加载元素
            var tableObjArr = [],
                trArr = [],
                thArr = [],
                tr,
                th,
                pStr,
                maxField,
                maxThField;
                maxString = 0;
            //遍历字段
            $.each(selectFields, function (i, v) {
                //加载th
                var columnName = v.columnName; //英文字段
                var columnChname = v.columnChname; //中文字段
                var currentName;
              
                //计算最大的tr
                if(isEnglish){
                	 maxThField = maxField = getStringLen(columnName);
                	 currentName = columnName;
                }else {
                	 maxThField = maxField = getStringLen(columnChname);
                	 currentName = columnChname;
                }
                var th = '<th class="columnName" data-columnName="' + columnName + '" data-columnChname="' + columnChname + '">' + currentName + '</th>';
                thArr.push(th);
                var showField;
                $.each(allFieldLog, function (i, v) {
                    showField = getStringLen(v[columnName]);
                    if (showField > maxField) {
                        maxField = showField
                    }
                });
                if(maxField === maxThField){
                	 maxString += maxField * 7.8;
                }else {
                	maxString += maxField * 7;
                }
               
            });

            if (allFieldLog.length === 10) {
                pStr = '<p class=\'fr\' style="padding-bottom:10px;"><a class=\'tableHref\' href=\'javascript:;\'>加载更多...</a></p>'
            } else {
                pStr = "";
            }

            $.each(allFieldLog, function (i, v) {
                var that = v;

                var tdString = "", tdArr = [], td;
                $.each(selectFields, function (i, v) {
                    td = '<td>' + that[v.columnName] + '</td>';
                    tdArr.push(td);
                    tdString += that[v.columnName];

                });
                if (i !== 0) {   //默认选中第一行
                    tr = '<tr>' + tdArr.join("") + '</tr>';
                } else {
                    tr = '<tr class="selectedLog">' + tdArr.join("") + '</tr>';
                }
                trArr.push(tr);

            });
            //表宽度设置
            var objSize = {
                'width': maxString + selectFields.length * 20 + 40,
                'height': allFieldLog.length > 5 ? 30 * 5 + 90 : allFieldLog.length * 30 + 90
            };
            obj.attributes.size = objSize;
            obj.attributes.attrs[".fobj"] = objSize;
            obj.attributes.attrs.div = objSize;
//tbody字符串
            var tbody = '<tbody>' + trArr.join("") + '</tbody>';
//table字符串
            var contentStr = '<table><thead><tr>' + thArr.join("") + '</tr></thead>' + tbody + '</table>' + pStr;

            //数据填充
            obj.attributes.attrs[".content"].html = contentStr;
            obj.attributes.attrs._tbody = trArr.join("");
            tableObjArr.push(obj);

            //加载线
            var fkObj = relationObj.fkObj;  //线的信息
            var dataObj = relationObj.dataObj;  //关联表的信息
            var fkField = "";
            $.each(fkObj.fkColumnList,function(i,v){
            	if(i === 0){
            		fkField = v.refColumnName + "-->"+ v.columnName;
            	}
            	else {
            		fkField += "& " +v.refColumnName + "-->"+ v.columnName;
            	}
            })
           
            var link = new joint.shapes.app.Link({
                "source": {"id": fkObj.resource},
                "target": {"id": fkObj.target + fkObj.fkId},
                connector: {name: 'rounded'},
                "id": fkObj.fkId,
                "attrs": {
                    ".connection": {
                        "stroke": "#20C1DD",
                        "stroke-width": 2,
                        "pointerEvents": "none"
                    },
                    ".marker-target": {
                        "fill": "#20C1DD",
                        "stroke": "#20C1DD",
                        "d": "M 10 0 L 0 5 L 10 10 z"
                    },
                }
                ,
                "labels": [
                    {"position": 0.8, "attrs": {"text": {"text": fkField,fontSize: 12},"rx": 120,"ry": 120,}, "rx": 120,"ry": 120,}
                ],
                "tools" : [{"position": 0.8,"offset": -20, "distance": 40}],
                '.tool-remove': false,
                'fkColumnList': fkObj.fkColumnList,
                'dataObj': dataObj
            });

            tableObjArr.push(link);
            graph.addCells(tableObjArr);
          //  $(".tool-options").remove();
            //页面元素布局
            var graphLayout = new joint.layout.TreeLayout({
                graph: graph,
                parentGap: 200,
                siblingGap: 120,
                direction: 'R'
            });
            graphLayout.layout();
        }
        else { //加载单个元素

            var trArr = [], tr, maxField0 = 0, maxField1 = 0, showField0, showField1;
            var objAllFields = {};

            $.each(startFields, function (i, v) {

                objAllFields[v.field] = v.value;

                tr = '<tr><td class="columnName" data-columnName="' + v.field + '" data-columnChname="' + (v.columnChname ? v.columnChname : v.field) + '">' + v.field + '</td><td>' + v.value + '</td></tr>';
                trArr.push(tr);

                showField0 = getStringLen(v.field);
                showField1 = getStringLen(v.value);

                if (showField0 > maxField0) {
                    maxField0 = showField0;
                }

                if (showField1 > maxField1) {
                    maxField1 = showField1;
                }

            });
            obj.attributes.attrs.currentLogObj = objAllFields;
            var maxString = maxField0 + maxField1;
            var objSize = {
                'width': maxString * 7 + 90,
                'height': startFields.length > 5 ? 30 * 5 + 30 : startFields.length * 30 + 40
            };
            console.log(objSize);
//表宽度设置
            obj.attributes.size = objSize;
            obj.attributes.attrs[".fobj"] = objSize;
            obj.attributes.attrs.div = objSize;

//tbody字符串
            var tbody = '<tbody>' + trArr.join("") + '</tbody>';
//table字符串
            var contentStr = '<table>' + tbody + '</table>';

//数据填充
            obj.attributes.attrs[".content"].html = contentStr;
            obj.attributes.attrs._tbody = trArr.join("");
            graph.addCells(obj);

        }
    }
})();

